using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using Spring.Context.Support;
using Xtee.Core.Adapter;
using Xtee.Core.Adapter.Config;
using Xtee.Core.Adapter.Service.Config;
using Xtee.Core.Envelope;

namespace Xtee.Core.Spring.Adapter.Config
{
    public class OperationCollection : BaseConfigurationElementCollection<XteeOperationConfigElement>, IOperationCollection
    {

        public OperationCollection()
        {
            XteeOperationConfigElement url =
                (XteeOperationConfigElement)CreateNewElement();
            // Add the element to the collection.
            Add(url);
        }



        public override object GetRequestProcessorService(ISoapEnvelope envelope)
        {

            var info = envelope.OperationInfo;

            if(info!=null)
            foreach (XteeOperationConfigElement element in this)
            {
                if (element.Producer == info.Producer &&
                    element.Name == info.Name &&
                    element.Version == info.Version)
                {
                     
                        return CreateServiceInstance(element.Service);
                }
            }

           
            return base.GetRequestProcessorService(envelope);


        }

        public virtual object CreateServiceInstance(string name)
        {
            return ContextRegistry.GetContext().GetObject(name);

        }

        protected override
          ConfigurationElement CreateNewElement(
          string elementName)
        {

            return new XteeOperationConfigElement(
               XteeOperationConfigElement.Parse(elementName).Producer,
               XteeOperationConfigElement.Parse(elementName).Name,
               XteeOperationConfigElement.Parse(elementName).Version);
        }


        protected override Object
            GetElementKey(ConfigurationElement element)
        {
            string unique = string.Format("{0}.{1}.{2}", ((XteeOperationConfigElement)element).Producer,
                           ((XteeOperationConfigElement)element).Name, ((XteeOperationConfigElement)element).Version);

            return unique;
        }
    }
}